$(document).ready(function($) {
	var fetched_images;
	var crop_sid,crop_cid,crop_type,crop_url,crop_imgpath,crop_imgpath_rel,crop_position,crop_style,crop_width,crop_height,crop_uid;

	var ptx_actions = {
		vcodeRefreshClick: function() {
			var link = (url_vcode.indexOf("?")>=0)?"&":"?";
			$(this).parent().find('img').attr("src", url_vcode+link+random(3));
			return false;
		},
		focusClick: function(e, target_id) {
			$('#' + target_id).focus();
			return false;
		},
		openLoginDialogClick: function() {
			openLoginDialog();
			return false;
		},
		openRegisterDialogClick: function() {
			showDialog('register_box',function(){
				$.oValidate('register_form');
			});
			return false;
		},
		openThemesClick: function(e, type,sid) {
			showDialog('theme_select',function(){
				$('#themetype').val(type);
				if(sid){
					$('#themestoreid').val(sid);
				}
				ajaxUpload(url_avatarupload, 'themebg_upload_btn', 'themebg_upload_file', 'themebg_img_div', false, 100, 100,function(result){
					var filepath = base_url+ 'data/attachments/tmp/'+ result.data.filename+ "." + result.data.ext;
					$('.content-inner').css('background-image','none');
					$('.content').css('background-image','url("'+filepath+'")');
					$('.content').css('background-repeat','repeat');
					$('.content').css('background-position','center center');
					$('#bgrepeat').attr('checked',true);
					$('#bgcenter').addClass('active');
				});

				ajaxUpload(url_avatarupload, 'headerbg_upload_btn', 'headerbg_upload_file', 'headerbg_img_div', false, 100, 100,function(result){
					var filepath = base_url+ 'data/attachments/tmp/'+ result.data.filename+ "." + result.data.ext;
					//$('.content-inner').css('background-image','none');
					$('.staruser-header').css('background-image','url("'+filepath+'")');
				});
				$.oValidate('theme_select_form');
			});
			return false;
		},
		bgrepeatClick: function() {
			if($(this).attr('checked')){
				$('.content').css('background-repeat','repeat');
			}else{
				$('.content').css('background-repeat','no-repeat');
			}
		},
		bglockClick: function() {
			if($(this).attr('checked')){
				$('.content').css('background-attachment','fixed');
			}else{
				$('.content').css('background-attachment','scroll');
			}
		},
		bgpositionClick: function(e,pos) {
			$('.content').css('background-position',pos+' center');
			$('#bgpos').val(pos);
		},
		headerrepeatClick: function() {
			if($(this).attr('checked')){
				$('.staruser-header').css('background-repeat','repeat');
			}else{
				$('.staruser-header').css('background-repeat','no-repeat');
			}
		},
		headerlockClick: function() {
			if($(this).attr('checked')){
				$('.staruser-header').css('background-attachment','fixed');
			}else{
				$('.staruser-header').css('background-attachment','scroll');
			}
		},
		headerpositionClick: function(e,pos) {
			$('.staruser-header').css('background-position',pos+' center');
			$('#headerpos').val(pos);
		},
		includeThemeClick: function(e, css,theme) {
			//$.includecss(css);
			$('#stylecontainer').attr('href',css);
			$('#usertheme').val(theme);
			return false;
		},
		openPublishDialogClick: function(e, type) {
			showDialog('publish',function(){
					$.oValidate('save_share_form');
					ajaxUpload(data_actions.attr('data-upload-url'), 'item_upload_btn', 'cover_filename', 'upload_imgview_div', false, 150, 180,null);
					getCategories('category_select_div', null, null);
					switchFetchType(type);
					$.oEditor('publish_editor',{
						id : 'publish_editor',
						className : 'editor',
						initialtext : '',
						editorcurrentheight : 130, 
						editorminheight : 130,
						editorcontroltop:false,
						editorid : 'editor'
					},true);
				});
		},
		collectPublishClick:function(e, type) {
				$.oValidate('save_share_form');
				ajaxUpload(data_actions.attr('data-upload-url'), 'item_upload_btn', 'cover_filename', 'upload_imgview_div', false, 150, 180,null);
				getCategories('category_select_div', null, null);
				switchFetchType(type);
				$.oEditor('publish_editor',{
					id : 'publish_editor',
					className : 'editor',
					initialtext : '',
					editorcurrentheight : 130, 
					editorminheight : 130,
					editorcontroltop:false,
					editorid : 'editor'
				},true);
		},
		postTGShareClick:function(e,type,id){
			showDialog('publish',function(){
				$.oValidate('save_share_form');
				$.oEditor('publish_editor',{
					id : 'publish_editor',
					className : 'editor',
					initialtext : '',
					editorcurrentheight : 130, 
					editorminheight : 130,
					editorcontroltop:false,
					editorid : 'editor'
				},true);
				ajaxUpload(data_actions.attr('data-upload-url'), 'item_upload_btn', 'cover_filename', 'upload_imgview_div', false, 150, 180,null);
				getCategories('category_select_div', null, null);
				switchFetchType('local_upload');
				if(type=='group') $("#groupid").val(id);
				else if(type=='topic') $("#topicid").val(id);
			});
		},
		joinGroupClick:function(e,gid){
			var data = {'groupid':gid};
			ajaxpost(url_joinGroup, data, 
			function(result){
				showSuccess(result.message,true);
				setTimeout(function(){
					window.location.reload();
				},1000);
			},
			function(result){
				showError(result.message);
			});
		},
		leaveGroupClick:function(e,gid){
			var data = {'groupid':gid};
			ajaxpost(url_leaveGroup, data, 
			function(result){
				showSuccess(result.message,true);
				setTimeout(function(){
					window.location.reload();
				},1000);
			},
			function(result){
				showError(result.message);
			});
		},
		sendMessageOpenClick:function(e,nickname){
			showDialog('message',function(){
				if(nickname) $('#send_message_form #message_user').val(nickname);
				$.oValidate('send_message_form');
			});
			
		},
		forwardingClick: function(e,sid) {
			getShare(sid,'forwarding','forwarding');
			return false;
		},
		forwardingSaveClick: function(e) {
			forwardingSave('forwarding_div');
			return false;
		},
		openAvatarClick: function() {
			showDialog('avatar',function(){
				ajaxUpload(url_avatarupload, 'avatar_upload_btn', 'avatar_upload_file', 'avatar_img_div', true, 180, 180,null);
			});
			return false;
		},
		openBannerClick: function(e,type,id) {
			showDialog('banner',function(){
				//ajaxUpload(url_avatarupload, 'banner_upload_btn', 'banner_upload_file', 'banner_img_div', true, 500, 133);
				if(type=='topic'){
					$('#banner_topicid').val(id);
					$('#banner_type').val("topic");
					$('#banner_img_div img').attr("src",$('#banner_topic_'+id).attr("src"));
					ajaxUpload(url_avatarupload, 'banner_upload_btn', 'banner_upload_file', 'banner_img_div', true, 590, 190,null);
				}else if(type=='group'){
					$('#banner_groupid').val(id);
					$('#banner_type').val("group");
					$('#banner_img_div img').attr("src",$('#banner_group_'+id).attr("src"));
					ajaxUpload(url_avatarupload, 'banner_upload_btn', 'banner_upload_file', 'banner_img_div', true, 180, 180,null);
				}else if(type=='store'){
					$('#banner_storeid').val(id);
					$('#banner_type').val("store");
					$('#banner_img_div img').attr("src",$('#banner_store_'+id).attr("src"));
					ajaxUpload(url_avatarupload, 'banner_upload_btn', 'banner_upload_file', 'banner_img_div', true, 180, 180,null);
				}
			});
			return false;
		},
		applyOpenClick: function(e,type,id) {
			var tpl = 'apply';
			if(type=='groupadmin'){
				tpl = 'apply_common';
			}
			showDialog(tpl,function(){
				$('#applytype').val(type);
				if(type=='groupadmin'){
					$('#apply_cid').val(id);
				}
				$.oValidate('apply_form');
			});
			return false;
		},
		starOpenClick: function(e, sid, uid, cid, path) {
			//starOpen(uid, cid, sid);
			$.oCrop('crop').starOpen(uid, cid, sid);
			return false;
		},
		closePushDialogClick: function() {
			getStaticDialog().hide();
			return false;
		},
		saveAvatarClick: function() {
			var filename = $('#avatar_upload_file').val();
			if (filename == null || filename == undefined || filename == '') {
				showError(tip_no_selection);
				return;
			}
			var img_avatar = $('#avatar_img_div .image_croped');
			var selection = crop_image.getSelection();
			var w = selection.x2 - selection.x1;
			var h = selection.y2 - selection.y1;
			var js_h = img_avatar.height();
			var js_w = img_avatar.width();
			saveCropAvatar(url_avatarsave, selection.x1, selection.y1, w, h, js_w, js_h, filename,'avatar');
			return false;
		},
		saveBannerClick: function() {
			var filename = $('#banner_upload_file').val();
			if (filename == null || filename == undefined || filename == '') {
				showError(tip_no_selection);
				return;
			}
			var img_avatar = $('#banner_img_div .image_croped');
			var selection = crop_image.getSelection();
			var w = selection.x2 - selection.x1;
			var h = selection.y2 - selection.y1;
			var js_h = img_avatar.height();
			var js_w = img_avatar.width();
			var type="banner";
			var purl=url_avatarsave;
			if($('#banner_type').val()=="topic"){
				type="topic";
			}else if($('#banner_type').val()=="group"){
				type="group";
			}else if($('#banner_type').val()=="store"){
				type="store";
			}
			saveCropAvatar(purl, selection.x1, selection.y1, w, h, js_w, js_h, filename,type);
			return false;
		},
		delCommentClick: function(e, sid, hash) {
			if(confirm(tip_confirmdelete)){
				deleteComment(sid, hash);
			}
			return false;
		},
		delalbumCommentClick: function(e, aid, cid) {
			if(confirm(tip_confirmdelete)){
				deleteAlbumComment(aid, cid);
			}
			return false;
		},
		delStoreCommentClick: function(e, sid,cid) {
			if(confirm(tip_confirmdelete)){
				deleteStoreComment(sid,cid);
			}
			return false;
		},
		addLikeClick: function(e, sid,appendid) {
			if($(this).hasClass('meta-liked')){
				removeLike('share',sid, appendid, url_shareremovelike, $(this));
			}else{
				addLike('share',sid, appendid, url_shareaddlike, $(this));
			}
			return false;
		},
		removeLikeClick: function(e, sid,appendid) {
			removeLike('share',sid, appendid, url_shareremovelike, $(this));
			return false;
		},
		socialShareClick: function(e, sid, type) {
			socialShare(sid,type);
			return false;
		},
		addLikeAlbumClick: function(e, aid) {
			addLike('album',aid, aid + '_album', url_albumaddlike);
			return false;
		},
		removeAlbumClick: function(e, aid) {
			if(confirm(tip_removealbum_confirm)){
				removeAlbum(aid, aid + '_album', url_albumdelete);
			}
			return false;
		},
		addLikeTopicClick: function(e, tid) {
			addLike('topic',tid, tid + '_topic', url_topicaddlike);
			return false;
		},
		removeLikeTopicClick: function(e, tid) {
			removeLike('topic',tid, tid + '_topic', url_topicremovelike);
			return false;
		},
		addLikestoreClick: function(e, tid) {
			addLike('store',tid, tid + '_store', url_storeaddlike);
			return false;
		},
		removeLikestoreClick: function(e, tid) {
			removeLike('store',tid, tid + '_store', url_storeremovelike);
			return false;
		},
		removeLikeAlbumClick: function(e, aid) {
			removeLike('album',aid, aid + '_album', url_albumremovelike);
			return false;
		},
		addCommentBoxClick: function(e, sid) {
			addCommentBox(sid);
			return false;
		},
		addCommentClick: function(e, sid, tpl, prepend) {
			var comments = $('#' + sid + '_commentbox').val();
			if(comments==null||comments==undefined||$.trim(comments)==''){
				showError(tip_cannotbenull);
				return false;
			}
			var type = 'comment';
			if (prepend == undefined || prepend == null) {
				prepend = false;
			} else {
				prepend = true;
			}
			addComment(tpl, sid, comments, type, prepend);
			return false;
		},
		addAlbumCommentClick: function(e, aid, tpl, prepend) {
			var comments = $('#' + aid + '_albumcommentbox').val();
			if(comments==null||comments==undefined||$.trim(comments)==''){
				showError(tip_cannotbenull);
				return false;
			}
			var type = 'albumcomment';
			if (prepend == undefined || prepend == null) {
				prepend = false;
			} else {
				prepend = true;
			}
			addComment(tpl, aid, comments, type, prepend);
			return false;
		},
		addStoreCommentClick: function(e, sid, tpl, prepend) {
			var comments = $.oFEditor('r_editor').getSubmitValue();
			if(comments==null||comments==undefined||$.trim(comments)==''){
				showError(tip_cannotbenull);
				return false;
			}
			var type = 'storecomment';
			if (prepend == undefined || prepend == null) {
				prepend = false;
			} else {
				prepend = true;
			}
			addComment(tpl, sid, comments, type, prepend);
			return false;
		},
		addDetailCommentClick: function(e, sid, tpl, prepend) {
			var comments = $.oFEditor('r_editor').getSubmitValue();
			if(comments==null||comments==undefined||$.trim(comments)==''){
				showError(tip_cannotbenull);
				return false;
			}
			var type = 'comment';
			if (prepend == undefined || prepend == null) {
				prepend = false;
			} else {
				prepend = true;
			}
			addComment(tpl, sid, comments, type, prepend);
			return false;
		},
		openCropClick: function(e, position, aspectRatio) {
			/*crop_position = position;
			openPushCropDialog(aspectRatio);*/

			$.oFCrop('crop').openCrop(position, aspectRatio);
			return false;
		},
		openPushDialogClick: function(e, sid, cid, path) {
			/*crop_sid = sid;
			crop_cid = cid;
			crop_type = 'home';
			crop_url = url_crophotshare;
			crop_imgpath = path;
			crop_imgpath_rel = path;
			findPushShare(sid, cid);*/
			$.oCrop('crop').findPushShare(sid, cid,path);
			return false;
		},
		starSaveClick: function(e,id) {
			var starOpenConfirm = $('#'+id);
			var star_reason = starOpenConfirm.find('.apply_reason').val();
			var cid = starOpenConfirm.find('.apply_cid').val();
			var uid = starOpenConfirm.find('.user_id').val();
			if(star_reason==null||star_reason==undefined||$.trim(star_reason)==''){
				starOpenConfirm.find('.error').html(tip_cannotbenull);
				return false;
			}
			$.oFCrop('crop').saveStaruser(cid, uid, star_reason);
		},
		applyStoreSaveClick: function(e, div_id) {
			var openDiv = $('#'+div_id);
			var txt = openDiv.find('.apply_reason').val();
			var cid = openDiv.find('.apply_sub_cid').val();
			if(txt==null||txt==undefined||$.trim(txt)==''){
				openDiv.find('.error').html(tip_cannotbenull);
				return false;
			}
			var apply_tpl = $('#apply_store_tpl');
			save_apply(cid, txt,"shop");
		},
		cropBtnClick: function(e) {
			/*var selection = crop_image.getSelection();
			var w = selection.x2 - selection.x1;
			var h = selection.y2 - selection.y1;
			var js_h = $('#crop_image_' + crop_sid).height();
			var js_w = $('#crop_image_' + crop_sid).width();
			pushCrop(crop_sid, crop_cid, crop_position, selection.x1, selection.y1, w, h, js_w, js_h);*/

			$.oFCrop('crop').crop();
			return false;
		},
		listTagsClick:function(e,cat_id,div_id){
			var div_elem = $('#'+div_id);
			getTags(cat_id,div_elem);
		},
		listCategoriesClick:function(e,div_id){
			getCategories(div_id, null, null);
		},
		editAlbumSaveClick: function(e, album_id,div_id) {
			var album_div = $('#'+div_id);
			var album_title = album_div.find('.album_title').val();
			var category_id = album_div.find('.category_select_id').val();
			editAlbumSave(album_id,album_title,category_id);
		},
		confirmRedirectClick: function(e, url, tip) {
			if(confirm(tip_confirm)){
				window.location.href = url;
			}
			return false;
		},
		editAlbumOpenClick: function(e, album_id, album_title,category_id,category_title) {
			fetchAjaxTpl('edit_album_tpl',{album_id:album_id,album_title:album_title},function(){getCategories('edit_album_tpl',category_id,category_title);});
		},
		albumItemClick: function(e, album_id, album_title,div_id) {
			albumSelect(album_id, album_title,div_id);
		},
		categoryItemClick: function(e, cat_id, cat_name,div_id,find_album) {
			categorySelect(cat_id, cat_name,div_id,find_album);
		},
		albumItemPopupClick: function(e,div_id) {
			albumItemPopup(div_id);
		},
		categoryItemPopupClick: function(e,div_id) {
			categoryItemPopup(div_id);
		},
		albumListPopupClick: function(e) {
			albumListPopup();
		},
		albumPopItemClick: function(e, album_id, album_title) {
			albumSelected(album_id, album_title);
		},
		categoryListPopupClick: function(e,id) {
			categoryListPopup(id);
		},
		categoryPopItemClick: function(e, cat_id, cat_name) {
			categorySelected(cat_id, cat_name,'category_select_div','album_select_div');
		},
		pushStarCatItemClick: function(e, cat_id, cat_name,div_id) {
			categorySelected(cat_id, cat_name,div_id,null);
		},
		openCatItemClick: function(e, cat_id, cat_name,div_id) {
			categorySelected(cat_id, cat_name,div_id,null);
		},
		albumPopCreateClick: function(e,div_id,uid) {
			createAlbumItem(div_id,uid);
		},
		switchPublishClick: function(e, type) {
			switchFetchType(type);
		},
		switchPushStyleClick: function(e, type) {
			//switchPushStyle(type);
			$.oFCrop('crop').switchPushStyle(type);
		},
		
		editFShareOpenClick: function(e, sid) {
			getShare(sid,'edit_forwarding','forwarding');
			return false;
		},
		editOShareOpenClick: function(e, sid) {
			//getShare(sid,'edit_item','edit_item');
			window.location.href = $(this).attr('data-edit');
			return false;
		},
		editShareClick: function(e, sid) {
			return false;
		},
		addFollowClick: function(e, fid) {
			addFollow(fid);
			return false;
		},
		removeFollowClick: function(e, fid) {
			removeFollow(fid);
			return false;
		},
		removePPClick: function(e) {
			$(this).parent().parent().fadeTo(1000, "hide", 0);
			setTimeout(function() {
				$(this).parent().parent().remove();
			},
			1000);
			return false;
		}
	};
	$('#body').actionController({
		controller: ptx_actions,
		events: 'click'
	});

	
	function bindParam(funcName){
	    var args=[];
	    for(var i=1;i<arguments.length;i++){
	        args.push(arguments[i]);
	    }
	    return function(){
	        funcName.apply(this,args);
	    };
	}
	
	function deleteAlbum(aid){
		var data= {'album_id': aid};
		ajaxpost(data_actions.attr('data-delalbum-url'), data, 
				function(result){
					getStaticDialog().hide();
					showSuccess(result.message,data_actions.attr('data-myalbum-url'));
				},
				function(result){
					showError(result.message);
				});
	}
	
	function editAlbumSave(aid,atitle,cid){
		var data= {'album_id': aid,'album_title': atitle,'category_id': cid};
		ajaxpost(data_actions.attr('data-editalbum-url'), data, 
				function(result){
					getStaticDialog().hide();
					showSuccess(result.message,data_actions.attr('data-myalbum-url'));
				},
				function(result){
					showError(result.message);
				});
	}
	
	function getShare(sid,type,tpl){
		var data= {'sid': sid};
		ajaxpost(url_getshare, data, 
				function(result){
					getTpl(tpl,function(){
						 var tpl_ins = $('#'+tpl+'_tpl');
						 var body = $(tpl_ins.html()).find('div.pbody');
						 var lis = $(Mustache.to_html(body.html(), result));
						 var width = body.attr('data-width');
						 var title = body.attr('data-title');
						 var css = body.attr('data-css-class');
						 var d=getStaticDialog().width(width).head(title).body(lis);
						 d.elem.addClass(css);
						 if(type=='forwarding'){
							 $('#forwarding_div').attr('data-sid',sid);
							 $('#forwarding_div').attr('data-uid',0);
							 //getCategories('forwarding_div', null, null);
							 $('.category-popbutton').popcategory({
									top: '0px',
									left: '0px',
									width: '370px',
									targetid: 'popcategory',
									tpl: 'deepcategory'},function(cid){
										getAlbums('forwarding_div',cid,null,null);
									});
							 d.show();
						 }else if(type=='edit_forwarding'){
							 d.head(tpl_ins.attr('data-edit-title'));
							 $('#forwarding_div').attr('data-sid',sid);
							 $('#forwarding_div').attr('data-edit','1');
							 getCategories('forwarding_div', result.data.share.category_id, result.data.share.category_name_cn);
							 d.show();
						 }else if(type=='edit_item'){
							 $('#item_detail_div').attr('data-sid',sid);
							 getCategories('item_detail_div', result.data.share.category_id, result.data.share.category_name_cn);
							 $.oValidate('edit_share_form');
							 if(result.data.share.share_type=='article'){
								 $('#image-area').css('display','none');
							 }else{
								 $('#image-area').css('display','inline-block');
							 }
								 
							 d.show();
							 var editor = $.oFEditor('m_editor');
							 if(editor){
								 //editor.config.initialtext = result.data.share.intro;
								 editor._createHTML();
							 }else{
								 $.oEditor('m_editor',{
										id : 'm_editor',
										className : 'editor',
										initialtext : '',
										editorcurrentheight : 130, 
										editorminheight : 130,
										editorcontroltop:false,
										editorid : 'meditor'
									});
							 }
						 }
					 });
				},
				function(result){
					showError(result.message);
				});
	}
	
	function addFollow(fid){
		var data= {'fid': fid};
		ajaxpost(url_addfollow, data, 
				function(result){
					$('.'+fid+'-relation').html(result.data);
				},
				function(result){
					showError(result.message);
				});
	}
	
	function removeFollow(fid){
		var data= {'fid': fid};
		ajaxpost(url_removefollow, data, 
				function(result){
					$('.'+fid+'-relation').html(result.data);
				},
				function(result){
					showError(result.message);
				});
	}
	
	function switchPushStyle(type){
		//$('#crop_dialog_tpl').attr('data-style',type);
		crop_style = type;
		$('#push_'+type).parent().find('.gallery').addClass("hide");
		$('#push_'+type).parent().parent().find('.active').removeClass("active");
		$('#push_'+type).removeClass("hide");
		$('#link_'+type).addClass("active");
	}
	
	function albumListPopup() {
		var elem = $('#album_select_div');
		$("body").click(function(e) {
			var eid = $(e.target).attr('id');
			if(eid=='album_name'||eid=='create_board'){
				return;
			}
			return !elem || elem.removeClass("btn_select_hover");
		});
		if (elem.hasClass("btn_select_disabled"))
		 return;
		elem.addClass("btn_select_hover");
	}
	
	function categoryListPopup(id) {
		var elem = $('#'+id);
		$("body").click(function(e) {
			return !elem || elem.removeClass("btn_select_hover");
		});
		if (elem.hasClass("btn_select_disabled"))
		 return;
		elem.addClass("btn_select_hover");
	}
	
	
	function categorySelected(cat_id, cat_name_cn,div_id,album_id) {
		var elem = $('#'+div_id);
		if (elem.hasClass("btn_select_hover")) {
			elem.removeClass("btn_select_hover");
		}
		elem.find('.category_select_title').html(cat_name_cn);
		elem.find('.category_select_id').val(cat_id);
		if(album_id!=null && album_id != undefined)
			getAlbumList(album_id,cat_id,null,null);
	}
	
	
	/*function starOpen(uid,cid,sid){
		var data= {'uid': uid,'sid': sid,'cid': cid};
		crop_sid = sid;
		crop_type = 'star';
		crop_uid = uid;
		crop_cid = cid;
		crop_url = url_starcovercrop;
		ajaxpost(url_getstaruser, data, 
				function(result){
					var tpl="star_open";
					getTpl(tpl,function(){
						var tpl_ins = $('#'+tpl+'_tpl');
						var body = $(tpl_ins.html()).find('div.pbody');
						var lis = $(Mustache.to_html(body.html(), result));
						var width = body.attr('data-width');
						var title = body.attr('data-title');
						var css = body.attr('data-css-class');
						var d=getStaticDialog().width(width).head(title).body(lis);
						d.elem.addClass(css);
						d.show();
						if(result.data.star_cover!=null&&result.data.star_cover!=undefined&&result.data.star_cover!=''){
							switchPushStyle(result.data.star_cover.style);
						}
						crop_imgpath = result.data.image_path;
					 });
				},
				function(result){
					var tpl="star_open_confirm";
					getTpl(tpl,function(){
						var tpl_ins = $('#'+tpl+'_tpl');
						var body = $(tpl_ins.html()).find('div.pbody');
						var lis = $(Mustache.to_html(body.html(), result.data));
						var width = body.attr('data-width');
						var title = body.attr('data-title');
						var css = body.attr('data-css-class');
						var d=getStaticDialog().width(width).head(title).body(lis);
						d.elem.addClass(css);
						d.show();
					 });
				});
	}*/
	
	function save_apply(cid, txt,type){
		var data= {'txt': txt,'rid': cid};
		ajaxpost(data_actions.attr("data-apply"+type+"-url"), data, 
				function(result){
					showSuccess(result.message);
					getStaticDialog().hide();
				},
				function(result){
					showError(result.message);
				});
	}
	
	function save_staruser(rid, uid, star_reason){
		var data= {'sreason': star_reason,'uid': uid,'rid': rid};
		ajaxpost(url_createstaruser, data, 
				function(result){
					var sid = crop_sid;
					$.oCrop('crop').starOpen(uid, rid, sid);
				},
				function(result){
					showError(result.message);
				});
	}
	
	
	function categoryItemPopup(div_id) {
		var div_elem = $('#' + div_id);
		var elem = div_elem.find('.category_select_list');
		$("body").click(function(e) {
			return !elem || elem.removeClass("btn_select_hover");
		});
		if (elem.hasClass("btn_select_disabled"))
		 return;
		elem.addClass("btn_select_hover");
	}
	
	function albumItemPopup(div_id) {
		var div_elem = $('#' + div_id);
		var elem = div_elem.find('.album_select_list');
		
		$("body").click(function(e) {
			var eid = $(e.target).attr('data-id');
			if(eid=='album_name'||eid=='create_board'){
				return;
			}
			return !elem || elem.removeClass("btn_select_hover");
		});
		if (elem.hasClass("btn_select_disabled"))
		 return;
		elem.addClass("btn_select_hover");
		
	}
	
	function forwardingSave(div_id) {
		var div_elem = $('#' + div_id);
		var cid = div_elem.find('.category_select_id').val();
		var aid = div_elem.find('.album_select_id').val();
		var sid = div_elem.attr('data-sid');
		var edit = div_elem.attr('data-edit');
		var purl = url_forwarding;
		if(edit==1){
			purl = url_editshare+'?act=save';
		}
		
		var data= {'sid': sid,
				'aid': aid,
				'cid': cid};
		ajaxpost(purl, data, 
				function(result){
					getStaticDialog().hide();
					showSuccess(result.message);
					check_message('reward',true,3000,1000);
				},
				function(result){
					showError(result.message);
				});
	}
	
	
	function deleteComment(sid, hash) {
		var data= {'sid': sid,'hash': hash};
		ajaxpost(url_deleteComment, data, 
				function(result){
					$('#comment_' + hash).fadeTo(1000, "hide", 0);
					setTimeout(function() {
						$('#comment_' + hash).remove();
					},
					1000);
					
				},
				function(result){
					showError(result.message);
				});
	}
	
	function deleteAlbumComment(aid, cid) {
		var data= {'cid': cid,'aid': aid};
		ajaxpost(url_deletealbumComment, data, 
				function(result){
					$('#albumcomment_' + cid).fadeTo(1000, "hide", 0);
					setTimeout(function() {
						$('#albumcomment_' + cid).remove();
					},
					1000);
					$('#waterfall').masonry('reload');
				},
				function(result){
					showError(result.message);
				});
	}
	
	function deleteStoreComment(sid,cid) {
		var data= {'storeid':sid,'cid': cid};
		ajaxpost(url_deletestoreComment, data, 
				function(result){
					$('#storecomment_' + cid).fadeTo(1000, "hide", 0);
					setTimeout(function() {
						$('#storecomment_' + cid).remove();
					},
					1000);
				},
				function(result){
					showError(result.message);
				});
	}
	
	
	function addCommentBox(id) {
		$('#waterfall').find('.commentdiv').addClass('hide');
		$('#' + id + '_commentdiv').removeClass('hide');
		$('#waterfall').masonry('reload');
		$('#' + id + '_commentbox').focus();
	}
	
	/*function openPushCropDialog(aspectRatio) {
		var ass = aspectRatio.split(':');
		crop_width=ass[0];
		crop_height=ass[1];
		
		var tpl="crop_dialog";
		var data = {
				'path': crop_imgpath,
				'sid': crop_sid
			};
		getTpl(tpl,function(){
			var tpl_ins = $('#'+tpl+'_tpl');
			var body = $(tpl_ins.html()).find('div.pbody');
			var lis = $(Mustache.to_html(body.html(), data));
			var width = body.attr('data-width');
			var title = body.attr('data-title');
			var css = body.attr('data-css-class');
			var d=getStaticDialog().width(width).head(title).body(lis);
			d.elem.addClass(css);
			d.show();
			
			$('#ui_puzz_dialog').imagesLoaded(function() {
				if (crop_image != null && crop_image != undefined) {
					crop_image.remove();
				}
				setTimeout(function() {
					crop_image = $('#crop_image_' + crop_sid).imgAreaSelect({
						zIndex: 2000,
						instance: true,
						aspectRatio: aspectRatio,
						show: true,
						x1: 5,
						y1: 5,
						x2: 100,
						y2: 100,
						handles: true
					});
				}, 500);
				
			});
		 });
	}*/
	
	/*function findPushShare(sid, cid) {
		var tpl="push_dialog";
		getTpl(tpl,function(tplexisted){
			//console.log(tplexisted);
			var data = {'cid':cid,'sid':sid};
			ajaxpost(url_categoryhotshare, data, 
				function(result){
					var tpl_ins = $('#'+tpl+'_tpl');
					var body = $(tpl_ins.html()).find('div.pbody');
					var pfunction = $(tpl_ins.html()).find('div.pfunction');
					//result.imagepath = crop_imgpath_rel;
					var lis = $(Mustache.to_html(body.html(), result));
					var width = body.attr('data-width');
					var title = body.attr('data-title');
					var css = body.attr('data-css-class');
					var d=getStaticDialog().width(width).head(title).body(lis);
					d.elem.addClass(css);
					d.show();
					switchPushStyle(result.data.style);
					//console.log(pfunction.text());
					if(!tplexisted&&pfunction){
						eval(pfunction.text());
					}
				},
				function(result){
					showError(result.message);
				});
			 
		 });
	}*/
	
	/*function pushCrop(sid, cid, position, x, y, w, h, js_w, js_h) {
		var crop_dialog = $('#crop_dialog_tpl');
		var ww = crop_width;
		var hh = crop_height;
		var type = crop_type;
		var style = crop_style;
		var uid = crop_uid;
		var data = {'sid':sid,'rid':cid,'cid':cid,'uid':uid,'position':position,'x':x,'y':y,'w':w,'h':h,'js_w':js_w,'js_h':js_h,'ww':ww,'hh':hh,'sy':style};
		ajaxpost(crop_url, data, 
				function(result){
					if(type=='home'){
						findPushShare(sid, cid);
					}else if(type=='star'){
						starOpen(uid,cid,sid);
					}
				},
				function(result){
					showError(result.message);
				});
		
	}*/
	
	
	function addComment(tpl, id, comments, type, prepend) {
		var tpl_e = $('#' + tpl+"_tpl");
		var reload = tpl_e.attr('reload');
		var data = {
				'id': id,
				'comment': comments
			};
		var purl = url_addcomment;
		var containerDiv = '#'+id+'_comments';
		var textarea = '#'+id+'_commentbox';
		if(type=='albumcomment'){
			purl = url_addalbumcomment;
			containerDiv = '#'+id+'_albumcomments';
			textarea = '#'+id+'_albumcommentbox';
		}else if(type=='storecomment'){
			purl = url_addstorecomment;
			containerDiv = '#'+id+'_storecomments';
		}
		ajaxpost(purl, data, 
				function(result){
						var new_comment = $(Mustache.to_html(tpl_e.html(), result));
						if (prepend) {
							$(containerDiv).prepend(new_comment);
						} else {
							$(containerDiv).append(new_comment);
						}
						new_comment.fadeIn(2000);
						if(tpl=='comment_detail'){
							$.oFEditor('r_editor').writeEditorContents('');
						}else{
							$(textarea).val('');
						}
						if (reload) {
							$('#'+id+'_commentdiv').addClass('hide');
							$('#waterfall').masonry('reload');
						}
						check_message('reward',true,3000,700);
				},
				function(result){
					showError(result.message);
				});
	}
	
	function getParamsOfShareWindow(a, b) {
		return ['toolbar=0,status=0,resizable=1,width=' + a + ',height=' + b + ',left=', (screen.width - a) / 2, ',top=', (screen.height - b) / 2].join('');
	}
	var share_sub_str = function(a, b, c) {
		if (a.length <= b) return a;
		var d = /https?:\/\/[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-_A-Z0-9a-z\$\.\+\!\*\/,:;@&=\?\~\#\%]*)*/gi;
		var e;
		while ((e = d.exec(a)) != null) {
			if (e.index < b && (e.index + e[0].length) > b) {
				return a.substr(0, e.index + e[0].length) + c;
			}
		}
		return a.substr(0, b) + c;
	};
	
	function socialShare(sid,type){
		var site_name = encodeURIComponent(tip_sitename);
		var window_name = 'social_share';
		var img = $('#'+sid+'_image').find('img');
		var img_url = "";
		var link = $('#'+sid+'_image').attr('href');
		if(img.length>0){
			img_url = $(img[0]).attr('orgin_src');
		}else{
			var video = $('#'+sid+'_image').find('.video_icon');
			if(video.length>0){
				link = $(video).attr('orgin_url');
				//img_url = $(video).attr('orgin_src');
			}
		}
		var desc_text = $('#'+sid+' .share_desc').text();
		var text = encodeURIComponent(share_sub_str(desc_text, 100, '...'));
		link = encodeURIComponent(link);
		img_url = encodeURIComponent(img_url);
		var summary=encodeURIComponent(desc_text);
		var title_social = encodeURIComponent(share_sub_str(desc_text, 30, '...'));
		var social_point = preg_replace(['{imgurl}','{text}','{url}','{sitename}','{summary}','{title}'],[img_url,text,link,site_name,summary,title_social],sharebutton[type]['link']);
		var social_window = getParamsOfShareWindow(sharebutton[type]['height'], sharebutton[type]['width']);
		window.open(social_point, window_name, social_window);
	}
	
	
	
	function ajaxUpload(url, btn_id, input_id, imageview_id, addCrop, mw, mh, successfun) {
		var button = $('#' + btn_id),
		interval;
		new AjaxUpload(button, {
			action: url,
			name: 'qqfile',
			responseType: 'json',
			onSubmit: function(file, ext) {
				button.text(tip_select_file);
				this.disable();
				interval = window.setInterval(function() {
					var text = button.text();
					if (text.length < 13) {
						button.text(text
						 + '.');
					} else {
						button.text(tip_uploading);
					}
				},
				200);
			},
			onComplete: function(file, response) {
				button.text(tip_select_file);
				window.clearInterval(interval);
				this.enable();
				if (response.success === !0) {
					var filename = response.data.filename
					 + "." + response.data.ext;
					var filepath = base_url
					 + 'data/attachments/tmp/'
					 + filename;
					if (addCrop) {
						$('#' + imageview_id).html('<img class="image_croped" src="'
						 + filepath
						 + '" style="max-width:' + mw + 'px;max-height: ' + mh + 'px;"/>');
						$('#' + input_id).val(filename);
						$('#' + imageview_id).imagesLoaded(function() {
							if (crop_image != null && crop_image != undefined) {
								crop_image.remove();
							}
							crop_image = $("#"+imageview_id+" .image_croped").imgAreaSelect({
								zIndex: 2000,
								instance: true,
								show: true,
								aspectRatio: mw+':'+mh,
								x1: 0,
								y1: 0,
								x2: 100,
								y2: 100,
								handles: true
							});
						});
					}else{
						$('#' + input_id).val(filename);
						$('#' + imageview_id).html('<img src="' + filepath + '"/>');
					}
					if(successfun!=null){
						successfun.call(url, response);
					}
				} else {
					showError(response.message);
				}
			}
		});
	}
	function saveCropAvatar(purl, x, y, w, h, js_w, js_h, filename,type) {
		show_loading('success');
		var extra="";
		if(type=="topic"){
			extra="&topicid="+$('#banner_topicid').val();
		}else if(type=="group"){
			extra="&groupid="+$('#banner_groupid').val();
		}else if(type=="store"){
			extra="&store="+$('#banner_storeid').val();
		}
		$.ajax({
			type: "post",
			url: purl,
			dataType: 'json',
			data: "x=" + x + "&y=" + y + "&w="
			 + w + "&h=" + h + "&js_w="
			 + js_w + "&js_h=" + js_h
			 + "&filename=" + filename
			 + "&type=" + type + extra
		}).error(function() {
			showError();
		}).success(function(result) {
			hide_loading();
			if (result.success === !0) {
				if (crop_image != null && crop_image != undefined)
				 crop_image.remove();
				if(type=='avatar'){
					$('#avatar_upload_file').val('');
					$('#avatar_img_div .image_croped').addClass('hide');
					$('#avatar_large_div').removeClass('hide').html('<img src="' + result.data.large + '?' + result.data.hash + '" width="150" height="150"/>');
					$('#avatar_middle_div').removeClass('hide').html('<img src="' + result.data.middle + '?'  + result.data.hash + '" width="50" height="50"/>');
					$('#avatar_small_div').removeClass('hide').html('<img src="' + result.data.small + '?' + result.data.hash  + '" width="16" height="16"/>');
					$('img[src="'+result.data.middle+'"]').attr('src',result.data.middle + '?'  + result.data.hash);
					$('img[src="'+result.data.large+'"]').attr('src',result.data.large + '?'  + result.data.hash);
					$('img[src="'+result.data.small+'"]').attr('src',result.data.small + '?'  + result.data.hash);
					$('#saveAvatarBtn').html('<button type="submit" data-action="closePushDialog" class="btn btn-primary"><span>'+tip_done+'</span></button>');
					check_message('reward',true,3000,1500);
				}else if(type=='banner'){
					$('#banner_upload_file').val('');
					$('#banner_img_div').removeClass('hide').html('<img src="'
					 + base_url_r
					 + result.data.avatar_local
					 + '_banner.jpg?'
					 + result.data.hash
					 + '" width="500" height="133"/>');
					$('#saveBannerBtn').html('<button type="submit" data-action="closePushDialog" class="btn btn-primary"><span>'+tip_done+'</span></button>');
				}else if(type=='topic'||type=='group'||type=='store'){
					var size = type=='topic'?'" height="133"/>':'" width="133" height="133"/>';
					var imgurl = base_url + result.data.banner+ '?'+ result.data.hash;
					$('#cropbannerimg input').val(result.data.banner);
					$('#cropbannerimg img').attr('src',imgurl);
					$('#bannerchanged').val("true");
					$('#banner_upload_file').val('');
					$('#banner_img_div').removeClass('hide').html('<img src="'+imgurl+ size);
					$('#saveBannerBtn').html('<button type="submit" data-action="closePushDialog" class="btn btn-primary"><span>'+tip_done+'</span></button>');
				}
			} else {
				showError(result.message);
			}
		});
	}
});